package com.example.consumer.config.i18n;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

/**
 * 国际化工具类
 */
@Component
public class MessageSourceUtil {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private MessageSource messageSource;

    public String getMessage(String code) {
        return getMessage(code, null);
    }

    public String getMessage(String code, Object[] args) {
        return getMessage(code, args, "");
    }

    public String getMessage(String code, Object[] args, String defaultMsg) {

        Locale locale = LocaleContextHolder.getLocale();
        // 从header获取lang语言信息,若存在则覆盖url中的语言
        if(StringUtils.isEmpty(request.getHeader("lang"))){
            String[] lang = request.getHeader("lang").split("_");
            locale = new Locale(lang[0],lang[1]);
        }

        return messageSource.getMessage(code, args, defaultMsg, locale);
    }

}